package com.dayuanit.dy16.atm.controller;

import com.dayuanit.dy16.atm.captcha.GifCaptcha;
import com.dayuanit.dy16.atm.dto.ResponseDTO;
import com.dayuanit.dy16.atm.entity.User;
import com.dayuanit.dy16.atm.service.IUserService;
import com.dayuanit.dy16.atm.vo.ForgetPwdRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class UserController extends BaseController {



    public UserController() {
        System.out.println("UserController()");
    }

    @Autowired
    private IUserService userService;

    @Value("${atm.avatar.path}")
    private String avatarPath;



    /**
     * 注册
     * @param username
     * @param pwd
     * @param confirmPwd
     * @return
     */
    @RequestMapping(value = "/user/signUp", method = RequestMethod.POST)
    public ResponseDTO signUp(String username, String pwd, String confirmPwd, String code) {

        String signUpCode = (String)httpSession.getAttribute("signUpCode");
        if (signUpCode == null || !signUpCode.equalsIgnoreCase(code)) {
            return ResponseDTO.fail("请重新输入验证");
        }

        userService.signUp(username, pwd, confirmPwd);

        //code消费掉后 及时清理掉 释放内存
        httpSession.removeAttribute("signUpCode");
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ResponseDTO login(String username, String pwd) {

        logger.info("usrename={} pwd={}", username, pwd);

        User user = userService.login(username, pwd);

        httpSession.setAttribute(user_login_flag, user);

        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/signOut", method = RequestMethod.POST)
    public ResponseDTO signOut() {
        //将session设置为失效
        httpSession.invalidate();
        return ResponseDTO.success();
    }

    @RequestMapping("/user/avatarUpload")
    public ResponseDTO avatarUpload(MultipartFile avatarFile) {
        if (avatarFile.isEmpty()) {
            return ResponseDTO.fail("上传失败");
        }

        String fileName = avatarPath + getUserId();
        System.out.println("fileName=" + fileName);
        try {
//            将头像写到磁盘的某个目录
            avatarFile.transferTo(new File(fileName));
            return ResponseDTO.success();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseDTO.fail("头像上传失败");
        }
    }

    @RequestMapping("/usre/showAavatar")
    public void showAavatar(HttpServletResponse response) {
        //文件在当前服务器磁盘的绝对路径
        String filePath = avatarPath + getUserId();

        try (FileInputStream fileInputStream = new FileInputStream(filePath);) {
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[2048];
            int length = -1;

            while (-1 != (length = fileInputStream.read(buff))) {
                outputStream.write(buff, 0, length);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/user/createCode", method = RequestMethod.GET)
    public void createCode(HttpServletResponse response) {
        //TODO 生成图形
        //TODO 生成验证码
        //TODO 将验证码放到图形里
        //TODO 将图形通过输出流 响应到终端

        GifCaptcha gifCaptcha = new GifCaptcha();
        try {
            gifCaptcha.out(response.getOutputStream());
            String code = gifCaptcha.text();
            System.out.println("code=" + code);

            httpSession.setAttribute("signUpCode", code);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/user/bindEmail")
    public ResponseDTO bindEmail(String email) {
        userService.bindEmail(getUserId(), email);

        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/forgetPassword", method = RequestMethod.POST)
    public ResponseDTO forgetPassword(String password, String confirmPassword) {
        ForgetPwdRequestVO forgetPwdRequestVO = (ForgetPwdRequestVO)httpSession.getAttribute("forgetPwdRequestVO");
        userService.changePasword(password, confirmPassword, forgetPwdRequestVO);
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/sendForgetPwdEmail", method = RequestMethod.POST)
    public ResponseDTO sendForgetPwdEmail(String email) {
        userService.sendForgetEmail(email);
        return ResponseDTO.success();
    }
}
